package cn.wzr.controller;

import cn.wzr.dao.impl.CommodityDao;
import cn.wzr.entity.Commodity;
import cn.wzr.global.Const;
import cn.wzr.util.CommonTools;
import cn.wzr.util.upload.UploadValidImage;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import static cn.wzr.util.CommonTools.isPositiveInt;

@MultipartConfig
@WebServlet(Const.WEBURL_SEPARATOR + Const.ACT_MULTCMDTS_UPLOAD)
public class MultiCmdtsUpload extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String contextPath = getServletContext().getRealPath(String.valueOf(Const.WEBURL_SEPARATOR));

        JSONObject resultJson = new JSONObject();
        String imgUCPerCmdtStr = request.getParameter("imgUploadCountPerCmdt");
        String[] cmdtsTxtArray = request.getParameter("cmdtsTxtArray").split(",");
//        String cmdtJsonArrayString = request.getParameter("cmdtJsonArray");
        try {
//			JSONArray a = (JSONArray)(new JSONParser().parse(cmdtJsonArrayString));
		
        int imgUCPerCmdt;   // 每件商品图片数量
        if (!isPositiveInt(imgUCPerCmdtStr)) {
            resultJson.put(Const.JS_P_ERRINFO, "传入的'每件商品图片数量'为非正整数值.");
            PrintWriter out = response.getWriter();
            out.print(resultJson.toJSONString());
            return;
        } else {
            imgUCPerCmdt = Integer.parseInt(imgUCPerCmdtStr);
        }

        // 取出上传对象, 过滤出文件对象
        Collection<Part> parts;
//        try {
            parts = request.getParts();

            UploadValidImage uploadValidImage = new UploadValidImage();
            int addup = 0;  // 由于每商品存在多张图片, 设置标志变量
            CommodityDao commodityDao = CommonTools.getCommodityDao(contextPath);
            
            for (Part part : parts) {
                // 遍历所有上传信息(含文件或文本)
                String contDisp;
                if (null != part && null != part.getContentType()) {
                    // 如果上传的对象为文件
                    contDisp = part.getHeader("content-disposition");
                    ++addup;
                    // 当前商品的图片
                    uploadValidImage.appendImage(contDisp);
                    String uploadRealFolder = (contextPath + uploadValidImage.getImageFolderPath());
                    CommonTools.makePathDirs(uploadRealFolder);  // 在磁盘上创建上传文件夹
                    String uploadRealPath = uploadRealFolder + uploadValidImage.getLastImageName();
                    // 上传文件
                    part.write(uploadRealPath);
                    if (addup == imgUCPerCmdt) {
                        // 当前商品图片已上传完毕
                        addup = 0;
                        // 修改数据库数据
                        // 获得数据库操作的DAO
//                        Commodity commodity = commodityDao.getByBarCode(uploadValidImage.getCmdtSN());
                        Commodity commodity = makeOneCmdtByUpload(cmdtsTxtArray, uploadValidImage);
                        if (null == commodity) {
                            // 出错啦
                            resultJson.put(Const.JS_P_ERRINFO, "没有从数据库中取到商品信息");
                            return;
                        }
//                        commodity.setImagePath(uploadValidImage.getLongImageNames());   // 修改图片路径名

                        Commodity oldcmdt = commodityDao.getByBarCode(commodity.getCmdtSN());
                        if(null != oldcmdt){
                        	commodityDao.delete(oldcmdt.getId().intValue());
//                        	commodityDao.update(commodity);	// 更新原有信息
                        }else{
                        }
                        commodityDao.add(commodity); // 新的商品信息写入数据库
                        uploadValidImage.reset();
                    }

                } else {
                    String contentDisposition = part.getHeader("Content-Disposition");
                    System.out.println(contentDisposition);
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (ServletException e1) {
            e1.printStackTrace();
//        } catch (ParseException e) {
//			e.printStackTrace();
		}
        resultJson.put("resultInfo", "上传成功");
        PrintWriter out = response.getWriter();
        out.print(resultJson);
    }


    /**
     * 通过上传的商品及图片信息产生一个商品对象
     * @param cmdtsTxtArray	所有的商品信息字符串数组
     * @param uploadValidImage	一个商品的图片信息
     * @return 在商品信息中遍历找到对应于图片的商品,生成一个商品对象返回
     */
	private Commodity makeOneCmdtByUpload(String[] cmdtsTxtArray, UploadValidImage uploadValidImage) {
		Commodity commodity;
		for(int i = 0; i<cmdtsTxtArray.length; ++i){
			commodity = new Commodity(cmdtsTxtArray[i]);
			if(commodity.getCmdtSN().equals(uploadValidImage.getCmdtSN())){
				commodity.setImagePath(uploadValidImage.getLongImageNames());
				return commodity;
			}
		}
		
		return null;
	}


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
